package com.hnust.service.impl;

import com.hnust.MainApp;
import com.hnust.api.TeacherApis;
import com.hnust.controller.personInfo.MyCourseGroupController;
import com.hnust.controller.personInfo.PersonDataController;
import com.hnust.domain.*;
import com.hnust.fx.DialogBuilder;
import com.hnust.service.TeacherServices;
import com.hnust.store.DataStore;
import com.hnust.view.MainView;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXSpinner;
import io.datafx.core.concurrent.ProcessChain;
import javafx.collections.FXCollections;
import javafx.scene.control.*;
import javafx.stage.Stage;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class TeacherServicesImpl implements TeacherServices {
    @Autowired
    private DataStore dataStore;
    @Autowired
    private TeacherApis teacherApis;
    @Autowired
    private MyCourseGroupController myCourseGroupController;
    private static final Logger logger = LogManager.getLogger(TeacherServicesImpl.class);

    @Override
    public void teacherLogin(Button loginBut, Stage stage, String username, String password) {
        ProcessChain.create()
                .addRunnableInPlatformThread(() -> {
                    JFXSpinner jfxSpinner=new JFXSpinner();
                    jfxSpinner.setRadius(6);
                    jfxSpinner.getStyleClass().add("blue-spinner");
                    loginBut.setText(" 登录中...");
                    loginBut.setDisable(true);
                    loginBut.setGraphic(jfxSpinner);
                })
                .addSupplierInExecutor(() -> teacherApis.teacherLogin(username,password))
                .addConsumerInPlatformThread((result)->{
                    if(result.getData()!=null){
                        dataStore.setToken(result.getData().getToken());
                        dataStore.setCollege_id(result.getData().getCollege_id());
                        dataStore.setCollege_name(result.getData().getCollege_name());
                        dataStore.setTeacher_id(result.getData().getTeacher_id());
                        dataStore.setTeacher_name(result.getData().getTeacher_name());
                        stage.close();
                        MainApp.switchView(MainView.class);
                    }else{
                        new DialogBuilder(loginBut).setTitle("提示").setMessage("账号或密码错误").
                                setPositiveBtn("确定","#ff3333").create();
                    }
                })
                .onException(e -> {
                    e.printStackTrace();
                    new DialogBuilder(loginBut).setTitle("提示").setMessage("无法连接到服务器，请检查网络").
                            setPositiveBtn("确定","#ff3333").create();
                })
                .withFinal(() -> {
                    loginBut.setGraphic(null);
                    loginBut.setText("登录");
                    loginBut.setDisable(false);
                }).run();
    }

    @Override
    public void teacherRegister(Button registerBtn, String name, String number, String password, String phone,
                                String email, String selectCollegeId) {
        ProcessChain.create().addRunnableInPlatformThread(() -> {
            JFXSpinner jfxSpinner=new JFXSpinner();
            jfxSpinner.setRadius(6);
            jfxSpinner.getStyleClass().add("blue-spinner");
            registerBtn.setText(" 注册中...");
            registerBtn.setDisable(true);
            registerBtn.setGraphic(jfxSpinner);
        }).addSupplierInExecutor(()-> teacherApis.register(name,number,password,phone,email,selectCollegeId))
        .addConsumerInPlatformThread((result)->{
            if(result.getData()){
                new DialogBuilder(registerBtn).setTitle("提示").setMessage("注册成功").
                        setPositiveBtn("确定","#3333cc").create();
            }else{
                new DialogBuilder(registerBtn).setTitle("提示").setMessage("注册失败").
                        setPositiveBtn("确定","#ff3333").create();
            }
        }).onException((e)->{
            new DialogBuilder(registerBtn).setTitle("提示").setMessage("无法连接到服务器，请检查网络").
                    setPositiveBtn("确定","#ff3333").create();
        }).withFinal(()->{
            registerBtn.setText("注册");
            registerBtn.setDisable(false);
        }).run();
    }

    @Override
    public void getAllCollege(ComboBox<College> registerCollege, Label registerCollegeLabel) {
        ProcessChain.create().addRunnableInPlatformThread(() -> {
            registerCollege.setItems(null);
            registerCollegeLabel.setText("正在获取学院列表...");
        }).addSupplierInExecutor(()-> teacherApis.getAllCollege())
                .addConsumerInPlatformThread((result)->{
                    registerCollege.setValue(new College(null,"获取学院成功"));
                    registerCollege.setItems(FXCollections.observableArrayList(result.getData()));
                    if(result.getData().size()!=0){
                        registerCollege.getSelectionModel().select(0);
                    }else{
                        registerCollegeLabel.setText("没有学院数据");
                    }
                }).onException((e)->{
            new DialogBuilder(registerCollege).setTitle("提示").setMessage("无法连接到服务器，请检查网络").
                    setPositiveBtn("确定","#ff3333").create();
        }).withFinal(()->{
            registerCollegeLabel.setText("所属学院");
        }).run();
    }

    @Override
    public void getCourseGroupInfo(ComboBox<GroupInfo> courseGroup, Label courseGroupLabel) {
        ProcessChain.create().addRunnableInPlatformThread(()->{
            courseGroup.setItems(null);
            courseGroupLabel.setText("获取中..");
        }).addSupplierInExecutor(()-> teacherApis.getInfo(dataStore.getTeacher_id()))
                .addConsumerInPlatformThread((result)->{
                    if(result.getData()!=null&&result.getData().getGroup().size()!=0){
                        courseGroup.setItems(FXCollections.observableArrayList(result.getData().getGroup()));
                        courseGroup.getSelectionModel().select(0);
                    }
                }).onException(e->{
                    e.printStackTrace();
            new DialogBuilder(courseGroupLabel).setTitle("提示").setMessage("无法连接到服务器，请检查网络").
                    setPositiveBtn("确定","#ff3333").create();
        }).withFinal(()->{
            courseGroupLabel.setText("课程组:");
        }).run();
    }

    @Override
    public void getCourseGroupDetailInfo(String selectCourseGroupId, Label leader_number, Label name,
                                         TableView<GroupMember> tableSize, int currentPage) {
        ProcessChain.create().addRunnableInPlatformThread(()->{
            name.setText("");
            leader_number.setText("获取数据中，请稍后...");
        }).addSupplierInExecutor(()-> teacherApis.getCourseInfo(dataStore.getTeacher_id(),selectCourseGroupId,currentPage))
                .addConsumerInPlatformThread((result)->{
                    logger.info(result);
                    if(result.getData()!=null&&result.getCode()==1){
                        GroupResult groupResult= result.getData();
                        myCourseGroupController.setPage(groupResult.getTotal());
                        GroupData data=groupResult.getGroupData();
                        name.setText(data.getLeaderName()!=null?"课程组组长:"+data.getLeaderName():"");
                        leader_number.setText(data.getLeaderNumber()!=null?"教工号:"+data.getLeaderNumber():"");
                        if(data.getGroupMember()!=null){
                            tableSize.setItems(FXCollections.observableList(data.getGroupMember()));
                        }else{
                            tableSize.setItems(null);
                        }
                    }else{
                        tableSize.setItems(null);
                        name.setText("");
                        leader_number.setText("");
                    }
                }).onException(e->{
                    e.printStackTrace();
            new DialogBuilder(leader_number).setTitle("提示").setMessage("无法连接到服务器，请检查网络").
                    setPositiveBtn("确定","#ff3333").create();
        }).run();
    }

    @Override
    public void getCourseTargetList(JFXButton showGoalBtn, String selectCourseId) {
        ProcessChain.create().addRunnableInPlatformThread(()->{
            showGoalBtn.setText("操作中...");
            showGoalBtn.setDisable(true);
        }).addSupplierInExecutor(()-> teacherApis.getCourseTargetList(dataStore.getTeacher_id(),selectCourseId))
                .addConsumerInPlatformThread((result)->{
                    if(result.getCode()==1){
                        //课程目标为1.1、 XXXX这种形式的信息
                        List<SubjectData> subjectData=result.getData();
                        subjectData=subjectData.stream().sorted(Comparator.comparing(SubjectData::getCourseNum))
                                .collect(Collectors.toList());
                        StringBuilder tmp= new StringBuilder();
                        for(SubjectData i:subjectData){
                            tmp.append(i.getCourseNum()).append(" : ").append(i.getContent()).append("\n\n");
                        }
                        new DialogBuilder(showGoalBtn).setTitle("课程目标").setMessage(tmp.toString()).
                                setPositiveBtn("确定","#3333cc").create();
                    }
        }).onException(e->{
            e.printStackTrace();
            new DialogBuilder(showGoalBtn).setTitle("提示").setMessage("无法连接到服务器，请检查网络").
                    setPositiveBtn("确定","#ff3333").create();
        }).withFinal(()->{
            showGoalBtn.setText("查看课程目标");
            showGoalBtn.setDisable(false);
        }).run();
    }

    @Override
    public void searchCourseGroupMember(JFXButton searchBtn, TableView<GroupMember> tableSize, String selectCourseGroupId, String text) {
        ProcessChain.create().addRunnableInPlatformThread(()->{
            searchBtn.setText("搜索中...");
            searchBtn.setDisable(true);
        }).addSupplierInExecutor(()-> teacherApis.getCourseTeaByName(selectCourseGroupId,text))
                .addConsumerInPlatformThread((result)->{
                    if(result.getCode()==1&&result.getData()!=null){
                        myCourseGroupController.setPage(result.getData().size());
                        tableSize.setItems(FXCollections.observableList(result.getData()));
                    }else{
                        tableSize.setItems(null);
                    }
                }).onException(e->{
                    e.printStackTrace();
            new DialogBuilder(searchBtn).setTitle("提示").setMessage("无法连接到服务器，请检查网络").
                    setPositiveBtn("确定","#ff3333").create();
        }).withFinal(()->{
            searchBtn.setText("搜索");
            searchBtn.setDisable(false);
        }).run();
    }
}
